package com.platform.pdf;

import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.IOException;

/**
 * ITextRenderer对象工厂,提供性能,加载中文字体集(大小20M),故增加对象池
 *
 * @author qijunyu
 */
public class ITextRendererObjectFactory extends
        BasePooledObjectFactory<ITextRenderer> {
    private static GenericObjectPool<ITextRenderer> iTextRendererObjectPool = null;

    /**
     * 获取对象池,使用对象工厂 后提供性能,能够支持 500线程 迭代10
     *
     * @return GenericObjectPool
     */
    static GenericObjectPool<ITextRenderer> getObjectPool() {
        synchronized (ITextRendererObjectFactory.class) {
            if (iTextRendererObjectPool == null) {
                GenericObjectPoolConfig<ITextRenderer> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
                iTextRendererObjectPool = new GenericObjectPool<>(new ITextRendererObjectFactory(), genericObjectPoolConfig);
            }
        }
        return iTextRendererObjectPool;
    }

    /**
     * 初始化
     */
    private static synchronized ITextRenderer createTextRenderer()
            throws IOException, com.lowagie.text.DocumentException {
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        addFonts(fontResolver);
        return renderer;
    }

    /**
     * 添加字体
     */
    private static void addFonts(ITextFontResolver fontResolver)
            throws IOException, com.lowagie.text.DocumentException {
        fontResolver.addFont("pdfConfig/fonts/SIMSUN.TTC", BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
    }

    @Override
    public ITextRenderer create() throws Exception {
        return createTextRenderer();
    }

    @Override
    public PooledObject<ITextRenderer> wrap(ITextRenderer obj) {
        return new DefaultPooledObject<>(obj);
    }

}
